#ifndef NET_BASE_CLIENT_CONNECTION_H
#define NET_BASE_CLIENT_CONNECTION_H

#include "net/base/connection.h"
#include "io/byte_stream.h"

/*
class ClientConnection {
 public:
  ClientConnection(const char* ip, int port);
  ~ClientConnection();
  void Connect();
  void Close();
  bool Send(const char* buffer, int size);
  int Recv(char* buffer, int maxsize);
  int sockfd();

 private:
  string ip_;
  int port_;
  ConnectionStatus status_;
  int sockfd_;
};*/

class ClientPollRunner;

class AsyncClientConnection {
 public:
  AsyncClientConnection(const char* ip, int port);
  ~AsyncClientConnection();
  void SetPollRunner(ClientPollRunner* poll_runner);
  void Connect();
  void Close();
  // Make it thread safe.
  int send_size();
  bool Send(const char* buffer, int size);
  virtual void HandleRecv(char* buffer, int size) = 0;
  virtual void HandleDisconnect() = 0;
  void HandleWrite();
  int sockfd();

 protected:
  ConnectionStatus status_;

 private:
  string ip_;
  int port_;
  int sockfd_;
  Mutex byte_stream_mutex_;
  ByteStream byte_stream_;
  ClientPollRunner* poll_runner_;

  friend class ClientPollRunner;
};

class ClientPollRunner {
 public:
  ClientPollRunner();
  void AddConnection(AsyncClientConnection* conn);
  void RemoveConnection(AsyncClientConnection* conn);
  void Loop();
  void SetExit();

 private:
  void CleanDisconnected();
  Mutex conn_mutex_;
  vector<AsyncClientConnection*> conn_;
  bool exit_;
};

#endif
